import { createStore, Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import _ from 'lodash'
import loginInfoModule from './modules/LoginInfo'
import { LocalStorageService } from '@/utils/storage'
import account from './modules/Account'
import app from './modules/App'
import * as Types from './types'
import { PACKAGE_NAME as key } from '@/global-config/const'
import { clearUcTokenByCookie } from '@/utils/utils'

type AnyObject = Record<string, any>
const { VITE_APP_ID } = import.meta.env

const commonState = {
  appId: VITE_APP_ID,
  menuList: [],
  enterpriseList: [],
  permissionsRoutersMap: {} // 权限字典
} as AnyObject
const options = {
  state: _.cloneDeep(commonState),
  modules: {
    loginInfoModule,
    account,
    app
  },
  mutations: {
    [Types.GLOBAL_DATA](state: AnyObject, data: AnyObject) {
      Object.assign(state, data)
    },
    [Types.RESET_STORE](state: AnyObject) {
      Object.assign(state, commonState)
      clearUcTokenByCookie() // 清理ucToken
    }
  },
  actions: {
    // eslint-disable-next-line consistent-return, no-empty-function
    async [Types.GETAREA]() {
    },
  },
}
export const store: Store<any> = createStore({
  ...options,
  plugins: [createPersistedState({ key })]
})

// 重置store
export function resetStore() {
  const cacheModules = _.cloneDeep(options.modules) as AnyObject
  const initStateData = {} as AnyObject
  Object.keys(cacheModules).forEach((key: any) => {
    initStateData[key] = cacheModules[key].state as AnyObject
  })
  Object.assign(initStateData, commonState)
  store.replaceState(initStateData)
  LocalStorageService.set(key, initStateData)
  clearUcTokenByCookie() // 清理ucToken
}
